<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Info\SelectClassify;
use App\Miya\Models\Classify;
use App\Miya\Models\Info;
use App\Miya\Models\Keyword;
use App\Miya\Models\Module;
use App\Miya\Models\ModuleType;
use App\Miya\Tools\ExtendTool;
use App\Miya\Tools\ImageTool;
use App\Miya\Tools\TagTool;
use App\Miya\Tools\TqlTool;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\App;
use Illuminate\Validation\Rule;

class InfoController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '模块信息';

    public function __construct()
    {
        if (!App::runningInConsole()) {
            $module = Module::find(request()->route('module'));
            $this->title = sprintf('%s 信息', $module->name);
        }
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Info());
        $grid->model()->with(['classify'])->has('classify')
            ->withoutGlobalScopes(['delay', 'status'])
            ->where('module_id', request()->route('module'));

        $grid->column('id', '序号');
        $grid->column('name', '信息')->display(function () {
            return sprintf(
                '<a href="%s" target="_blank">%s <i class="fa fa-link"></i></a>',
                $this->url(),
                $this->name
            );
        });
        $grid->column('keyword_id', '关键词')
            ->editable('select', Keyword::pluck('keyword', 'id'));
        $grid->column('classify_id', '分类')->display(function () {
            return $this->classify->name;
        })->label();
        $grid->column('status', '状态')
            ->radio(Info::$states);
        $module = Module::find(request()->route('module'));
        $type = Info::$rankTypes[$module->info_rank_type];
        $grid->column('rank', '优先级')
            ->editable()->sortable()
            ->help('当前前端信息排序方式:<br>' . $type);
        $grid->column('avatar', '封面图')->light_box(['height' => 18]);
        $grid->column('updated_at', '更新时间')->display(function () {
            return $this->updated_at->diffForHumans();
        })->label();

        $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
            $batch->add(new SelectClassify());
        });

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();

            $filter->like('name', '信息名称');
            $filter->equal('status', '状态')->select(Info::$states);
            $filter->equal('keyword_id', '关键词')->select(Keyword::pluck('keyword', 'id'));
            $filter->equal('tag', '标签');
            $filter->equal('classify_id', '分类')->select($this->classifySelectOptions());
            $filter->where(function ($query) {
                $query->whereHas('info_types', function ($query) {
                    $query->where('value', $this->input);
                });
            }, '属性')->select($this->typeSelectOptions());
        });

        return $grid;
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit(request()->route('info')));
    }

    public function update($id)
    {
        return $this->form()->update(request()->route('info'));
    }

    public function destroy($id)
    {
        return $this->form()->destroy(request()->route('info'));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Info());

        $module = Module::find(request()->route('module'));

        if ($form->isCreating()) {
            $form->hidden('module_id')->value(request()->route('module'));
        }
        $form->tab('基础设置', function (Form $form) {
            $form->select('classify_id', '分类')
                ->options($this->classifySelectOptions())->rules(['required']);
            $form->text('name', '信息名称')->rules(['required']);

            $form->radio('push_delay_task', '开始延时任务')
                ->help('开启延时任务,预计 ' . $this->buildDelayDay()->diffForHumans() . ' 显示')
                ->default(2)->options(Info::$states);
            $avatarFormObject = $form->image('avatar', '封面图')
                ->uniqueName()->removable()->move(getMovePath('infos'));
            if (config('setting.open_watermark') == 1) {
                $avatarFormObject->insert(
                    public_path('uploads/' . config('setting.watermark_image')),
                    config('setting.watermark_position')
                );
            }
            $form->UEditor('content', '内容');
        })->tab('高级设置', function (Form $form) use ($module) {
            if ($form->isCreating()) {
                $form->text('tag', '标签')->rules([Rule::unique('infos')]);
            } elseif ($form->isEditing()) {
                $info = Info::find(request()->route('info'));
                $form->text('tag', '标签')->rules([Rule::unique('infos')->ignore($info)]);
            }
            $form->select('keyword_id', '关键词')->rules(['required'])
                ->options(Keyword::pluck('keyword', 'id'))
                ->default(app('admin_keyword')->autoSelect('infos')->id);
            $imagesFormObject = $form->multipleImage('images', '多图展示')
                ->uniqueName()->removable()->move(getMovePath('infos'));
            if (config('setting.open_watermark') == 1) {
                $imagesFormObject->insert(
                    public_path('uploads/' . config('setting.watermark_image')),
                    config('setting.watermark_position')
                );
            }
            $form->radio('status', '状态')->default(1)->options(Info::$states);
            $form->select('tql', '信息模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'infos'))
                ->default($module->info_tql);
            $form->select('wap_tql', '移动端信息模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'infos', 'wap'))
                ->default($module->wap_info_tql);
            $form->slider('rank', '优先级')->default(1)->options([
                'max' => 100,
                'min' => 1,
                'step' => 1,
            ]);
            $form->number('page_views', '访问量')->default(0);
        })->tab('延时设置', function (Form $form) {
            $form->radio('is_delayed', '是否开启延时展示')->default(2)->options(Info::$states);
            $form->datetime('delayed_at', '展示时间');
        })->tab('页面设置', function (Form $form) {
            $form->text('title', '页面标题');
            $form->list('custom_keywords', '自定义关键词');
            $form->textarea('description', '描述');
        })->tab('属性设置', function (Form $form) use ($module) {
            $form->hasMany('info_types', '信息属性', function (Form\NestedForm $form) use ($module) {
                $form->hidden('module_id')->value($module->id);
                $form->select('module_type_id', '属性')->help('请勿重复设置同一个属性!')
                    ->load('value', '/api/admin/module_types/get-values')
                    ->options(ModuleType::where('module_id', $module->id)->pluck('name', 'id'));
                $form->select('value', '属性值')->options($this->typeSelectOptions());
            });
        })->tab('拓展设置', function (Form $form) use ($module) {
            $form->embeds('extends', '拓展信息', function (Form\EmbeddedForm $form) use ($module) {
                ExtendTool::buildForm($form, $module->info_extends);
            });
        });

        $form->saving(function (Form $form) {
            if ($form->name && !$form->tag) {
                $form->tag = TagTool::makeTag($form->name, true);
            }

            if ($form->push_delay_task == 1) {
                if ($form->is_delayed == 2) {
                    $form->is_delayed = 1;
                    $form->delayed_at = $this->buildDelayDay();
                }
            } else {
                if ($form->is_delayed == 1) {
                    $form->is_delayed = 2;
                    $form->delayed_at = null;
                }
            }

            //关键词被删除情况下,重新设置关键词
            $keyword = Keyword::find($form->keyword_id);
            if (!$keyword) {
                $form->keyword_id = app('admin_keyword')->autoSelect('classifies')->id;
            }
        });

        $form->saved(function (Form $form) {
            //切换操作完成后的跳转地址 list:列表页 now:当前页
            if (config('miya.info_save_redirect_type') == 'now') {
                $url = request()->header('referer');
                return redirect($url)->with(admin_toastr('信息操作成功!'));
            }

            //处理封面和多图
            ImageTool::optimize($form->model()->avatar);
            foreach ($form->model()->images as $path) {
                ImageTool::optimize($path);
            }
        });

        return $form;
    }

    protected function classifySelectOptions()
    {
        $classifies = Classify::selectOptions(function ($query) {
            return $query->where('module_id', request()->route('module'));
        });
        unset($classifies[0]);

        return $classifies;
    }

    protected function typeSelectOptions()
    {
        $optionData = [];
        ModuleType::pluck('values')->each(function ($values) use (&$optionData) {
            array_map(function ($value) use (&$optionData) {
                $optionData[$value['hash']] = $value['value'];
            }, $values);
        });

        return $optionData;
    }

    protected function buildDelayDay()
    {
        $tasks = Info::where('push_delay_task', 1)->where('delayed_at', '>', now())->count();
        $delayDays = config('delay_task.interval_day') * (1 + (int)($tasks / config('delay_task.one_time_num')));
        return now()->addDays($delayDays);
    }
}
